<template>
  <view class="main-container" style="background-color: #dd302c">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-left" @tap="handleBack">
        <u-icon name="arrow-left" color="#FFF" size="20"></u-icon>
      </view>
      <view class="nav-title">人工智能易学大模型</view>
      <view class="nav-right" @tap="handleBack">
        <u-icon name="close" color="#FFF" size="20"></u-icon>
      </view>
    </view>

    <view class="box-content" style="min-height: 60vh">
      <view class="feature-section">
        <view class="tabs-container">
          <view class="tabs-row">
            <view
              v-for="(tab, index) in otherResultInfo"
              :key="index"
              class="tab"
              :class="{ active: currentMarriageTab === index }"
              @tap="changeMarriageTab(index)"
            >
              {{ tab.name }}
              <view
                class="tab-underline"
                :class="{ active: currentMarriageTab === index }"
              ></view>
            </view>
          </view>
          <view class="tab-content">
            <view v-if="!currentTabPaid" class="tab-item">
              <view class="title-icon">
                <view class="title-text">{{
                  otherResultInfo[currentMarriageTab].name
                }}</view>
              </view>
              <view class="prices-section">
                <view class="price-section">
                  <view class="price-wrapper">
                    <text class="original-price">总计￥ 99</text>
                    <text class="current-price">优惠价：9.9元</text>
                  </view>
                </view>
                <view class="tab-item-content" style="text-align: center"
                  >请支付后查看详细内容...</view
                >
                <view class="pay-now-btn" @tap="createOrder({goodsId: '20250618007', payAmount: '29', index:4,})">
                  <text>立即支付</text>
                </view>
                <view class="user-count"
                  >已有
                  <span style="color: #dd302c">{{
                    Math.floor(userCount * 0.64)
                  }}</span
                  >人完成支付，获取了姻缘分析结果
                </view>
                <view class="otherComp-image">
                  <image
                    :src="pageData.feature.otherComp"
                    mode="aspectFit"
                  ></image>
                </view>
              </view>
            </view>
            <view v-else>
              <view
                v-for="(item, index) in otherResultInfo[currentMarriageTab]
                  .content"
                class="tab-item"
              >
                <view class="title-icon">
                  <view class="title-text">{{ item.title }}</view>
                </view>
                <view class="tab-item-content">{{ item.thinkContent }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <view class="footer-info">
      <text class="sub-text"
        >本站所有测试项目，均由AI大模型根据传统易学八字自动测算，如有雷同，纯属巧合。测算结果不作为您真正的人生指导策划，仅作娱乐参考!某些民俗占卜，仅作研究之用，请勿迷信!</text
      >
    </view>
    <!-- 客服助手 -->
    <floating-image ref="floatingImage" />
    <floating-report ref="report" />
  </view>
</template>

<script>
import { getOtherInfo, queryOrder } from "@/api/fortune";
import { mapGetters } from "vuex";
import pageData from "./data.js";
import { trackPageView, trackButton, trackPayment } from "@/utils/track";

export default {
  name: "PayPage",
  data() {
    return {
      // 引用页面数据
      pageData,
      // 当前选中的婚姻透视tab
      currentMarriageTab: 0,
      // 价格相关
      originalPrice: pageData.price.original,
      currentPrice: pageData.price.current,
      pageViewTracker: null,
      currentorderNo: "",
      payIndex: 0,
    };
  },

  computed: {
    ...mapGetters("fortune", ["userInfo", "otherResultInfo"]),
    ...mapGetters("system", ["userCount"]),
    ...mapGetters("payment", ["getPayStatus"]),
    currentTabPaid() {
      return this.getPayStatus("other", this.currentMarriageTab);
    },
  },
  onShow() {
    // 使用工具函数获取解码后的订单号
    const decodedOrderNo = this.$utils.getDecodedUrlParam("orderNo");
    const decodedIndex = this.$utils.getDecodedUrlParam("index");
    if (decodedOrderNo) {
      // 清除URL参数中的orderNo，避免重复处理
      const newUrl = window.location.pathname;
      window.history.replaceState({}, document.title, newUrl);
      this.payIndex = decodedIndex;
      // 记录订单号
      this.currentorderNo = decodedOrderNo;

      this.changeMarriageTab(decodedIndex);

      // 直接验证支付状态
      this.confirmPayment();
    }
  },
  onLoad(options) {
    // 设置初始tab索引
    if (options.index) {
      this.currentMarriageTab = parseInt(options.index);
    }
  },
  mounted() {
    // 数据加载完成后显示悬浮图片
    this.$nextTick(() => {
      this.$refs.floatingImage.show();
    });
    // 启动页面浏览埋点计时
    this.pageViewTracker = trackPageView({
      reportKey: "进入其他运势页",
      reportVal: "浏览",
      pageName: "其他运势页",
    });
    this.pageViewTracker.start();
  },
  onHide() {
    if (this.pageViewTracker) this.pageViewTracker.stop();
  },
  onUnload() {
    if (this.pageViewTracker) this.pageViewTracker.stop();
  },
  methods: {
    // 切换婚姻透视tab
    changeMarriageTab(index) {
      this.currentMarriageTab = index;
    },

    // 处理返回和关闭
    handleBack() {
      uni.navigateTo({
        url: "/pages/payResult/report",
      });
    },

    createOrder() {
      // 获取当前tab商品信息
      const item = this.pageData.serviceItems[this.currentMarriageTab];
      uni.showLoading({ title: "正在创建订单...", mask: true });
      this.payIndex = this.currentMarriageTab;
      const orderParams = {
        goodsId: item.goodsId,
        payAmount: item.price,
        redirect: `/pages/payResult/otherPay`,
        type: "other",
        index: this.payIndex,
      };
    
      this.$commonPay(orderParams);
      uni.hideLoading();
    },
    async confirmPayment() {
      uni.showLoading({ title: this.pageData.payMessages.loading, mask: true });
      this.verifyPaymentStatus(this.currentorderNo, async (success) => {
        uni.hideLoading();
        if (success) {
          try {
            const res = await getOtherInfo();
            this.setOtherResultInfo(res.data);
            trackPayment({
              reportKey: "支付成功",
              reportVal: this.currentorderNo,
              pageName: "其他运势页",
            });
            // 设置支付状态
            this.$store.dispatch("payment/setPayStatus", {
              type: "other",
              status: true,
              index: this.payIndex,
            });
            this.$show.showToast(this.pageData.payMessages.success, {
              icon: "success",
              success: () => {
                uni.navigateTo({
                  url: `/pages/payResult/otherPay?index=${this.payIndex}`,
                });
              },
            });
          } catch (e) {
            console.log(e);
            this.$show.showToast("数据加载失败，请稍后再试");
          }
        } else {
          this.$show.showToast(this.pageData.payMessages.failure, {
            icon: "error",
          });
          trackPayment({
            reportKey: "支付失败",
            reportVal: this.currentorderNo,
            pageName: "其他运势页",
          });
        }
      });
    },
    verifyPaymentStatus(orderNo, callback) {
      queryOrder(orderNo)
        .then((res) => {
          if (res.code === 0 && res.data && res.data.orderPayStatus === 1) {
            callback(true);
          } else {
            callback(false);
          }
        })
        .catch((err) => {
          console.error(pageData.payMessages.failure, err);
          callback(false);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./result.scss";
.pay-now-btn {
  margin: 30rpx auto 0 auto;
  width: 60%;
  background: #dd302c;
  color: #fff;
  text-align: center;
  border-radius: 40rpx;
  padding: 20rpx 0;
  font-size: 32rpx;
  font-weight: 500;
}
</style>
